//
//  StatusCell.swift
//  MyWeiboApp
//
//  Created by 胡海波 on 15/7/2.
//  Copyright © 2015年 胡海波. All rights reserved.
//

import UIKit
import FFAutoLayout
import SDWebImage


let HBStatusNormalCellReusedIdentified = "HBStatusNormalCellReusedIdentified"
let HBStatusForwardCellReusedIdentified = "HBStatusForwardCellReusedIdentified"


let HBPictureViewCellReusedIdentified = "HBPictureViewCellReusedIdentified"

protocol StatusCellDelegate: NSObjectProtocol {

    func StatusCellDidSelectedPhotoes(cell: StatusCell,photoIndex: Int)

}

class StatusCell: UITableViewCell,UICollectionViewDataSource,UICollectionViewDelegate{

    // 定义代理属性
    weak var photoDelegate: StatusCellDelegate?

    private var picWidthCon: NSLayoutConstraint?
    private var picHightCon: NSLayoutConstraint?
    private var topCon: NSLayoutConstraint?

    // 转发微博标签
    var forwardLable: UILabel?


    // 微博数据模型
    var status: Status? {

        didSet {

            forwardLable?.text = (status?.retweeted_status?.user?.name ?? "") + ": " + (status?.retweeted_status?.text ?? "")

            iconView.sd_setImageWithURL(status!.user?.profileURL)
            nameLable.text = status?.user?.name
            verifyIconView.image = status!.user?.verifiedImage
            memberIconView.image = status!.user?.mbImage

            timeLable.text = "刚刚"
            sourceLable.text = "来自 微博"
            contentLable.text = status?.text
            contentLable.preferredMaxLayoutWidth = UIScreen.mainScreen().bounds.width - 16

            let result = calcPictureViewSize(status!)

            topCon?.constant = result.viewSize.height == 0 ? 0 : 12
            picWidthCon?.constant = result.viewSize.width
            picHightCon?.constant = result.viewSize.height
            pictureLayout.itemSize = result.itemSize

            pictureView.reloadData()

        }
    }

    // 创建函数返回cell重用标识
    class func cellReusedIdentifier(status:Status) -> String {

        return status.retweeted_status != nil ? HBStatusForwardCellReusedIdentified : HBStatusNormalCellReusedIdentified
    }

    // 设置行高
    func rowHight(status: Status) -> CGFloat{

        self.status = status

        // 更新布局
        layoutIfNeeded()

        return CGRectGetMaxY(footerView.frame)

    }

    // MARK: -- 计算配图大小
    private func calcPictureViewSize(status: Status) -> (viewSize:CGSize, itemSize: CGSize) {

        let itemSize = CGSize(width: 90, height: 90)
        let margin: CGFloat = 10

        // 1. 获取图片数量
        let count = status.calPictureURLs?.count ?? 0

        // 2. 没有图片
        if count == 0 {
            return (CGSizeZero,itemSize)
        }

        // 3. 只有一张图片
        if count == 1 {
            // 拿到image
            let key = status.calPictureURLs![0].absoluteString
            let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
            // 返回image大小
            return (image.size,image.size)
        }

        // 4. 4张图片
        if count == 4 {
            let wh = itemSize.width * 2 + margin

            return (CGSize(width: wh, height: wh),itemSize)
        }

        // 多张图片
        let colCount = 3
        let row = (count - 1) / colCount + 1

        let w = itemSize.width * CGFloat(colCount) + margin * CGFloat(colCount - 1)
        let h = CGFloat(row) * itemSize.height + CGFloat(row - 1) * margin

        return (CGSize(width: w, height: h),itemSize)
    }

    // 计算配图约束
    func calPictureCons(cons:[NSLayoutConstraint]){

        topCon = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Top)
        picWidthCon = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Width)
        picHightCon = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Height)

    }

    // MARK: -- UICollectionView 数据源实现
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        return status?.calPictureURLs?.count ?? 0
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(HBPictureViewCellReusedIdentified, forIndexPath: indexPath) as! StatusPictureCell

        cell.imageURL = status!.calPictureURLs![indexPath.item]
        
        pictureView.backgroundColor = (status?.retweeted_status != nil) ? (UIColor(white: 0.9, alpha: 1.0)) : (UIColor.whiteColor())

        return cell
    }

    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {


        photoDelegate?.StatusCellDidSelectedPhotoes(self, photoIndex: indexPath.item)
    }

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {

        super.init(style: style, reuseIdentifier: reuseIdentifier)

        let mainScreenWidth = UIScreen.mainScreen().bounds.size.width

        // 顶部视图
        let topView = UIView()
        topView.backgroundColor = UIColor(white: 0.2, alpha: 1.0)
        addSubview(topView)
        topView.ff_AlignInner(ff_AlignType.TopLeft, referView: self, size: CGSize(width: mainScreenWidth, height: 5))
        
        addSubview(iconView)
        addSubview(nameLable)
        addSubview(memberIconView)
        addSubview(verifyIconView)
        addSubview(timeLable)
        addSubview(sourceLable)
        addSubview(contentLable)
        addSubview(pictureView)
        addSubview(footerView)


        // 设置配图
        preparePictureView()


        // 设置自动布局
        iconView.ff_AlignInner(ff_AlignType.TopLeft, referView: self, size: CGSizeMake(34, 34), offset: CGPoint(x: 12, y: 22))

        nameLable.ff_AlignHorizontal(ff_AlignType.TopRight, referView: iconView, size: nil, offset: CGPoint(x: 12, y: 0))
        memberIconView.ff_AlignHorizontal(ff_AlignType.CenterRight, referView: nameLable, size: nil, offset: CGPoint(x: 12, y: 0))
        verifyIconView.ff_AlignInner(ff_AlignType.BottomRight, referView: iconView, size: nil, offset: CGPoint(x: 8, y: 8))
        timeLable.ff_AlignHorizontal(ff_AlignType.BottomRight, referView: iconView, size: nil, offset: CGPoint(x: 12, y: 0))
        sourceLable.ff_AlignHorizontal(ff_AlignType.CenterRight, referView: timeLable, size: nil, offset: CGPoint(x: 12, y: 0))
        contentLable.ff_AlignVertical(ff_AlignType.BottomLeft, referView: iconView, size: nil, offset: CGPoint(x: 0, y: 12))

        // 设置底部视图布局
        footerView.ff_AlignVertical(ff_AlignType.BottomLeft, referView: pictureView, size: CGSize(width: mainScreenWidth, height: 40), offset: CGPoint(x: -12, y: 12))


    }
    ///  准备配图视图
    private func preparePictureView() {


        // 设置数据源
        pictureView.dataSource = self
        pictureView.delegate = self

        // 注册可重用cell
        pictureView.registerClass(StatusPictureCell.self, forCellWithReuseIdentifier: HBPictureViewCellReusedIdentified)

        // 设置layout
        pictureLayout.minimumInteritemSpacing = 10
        pictureLayout.minimumLineSpacing = 10
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }


    // 头像
    lazy var iconView = UIImageView()

    // 昵称标签
    lazy var nameLable = UILabel(color: UIColor.darkGrayColor(), fontSize: 14)
    // 会员图像
    lazy var memberIconView: UIImageView = UIImageView(image: UIImage(named: "common_icon_membership_level1"))
    // 认证图标
    lazy var verifyIconView: UIImageView = UIImageView(image: UIImage(named: "avatar_grassroot"))
    // 时间标签
    lazy var timeLable = UILabel(color: UIColor.orangeColor(), fontSize: 10)
    // 来源
    lazy var sourceLable = UILabel(color: UIColor.darkGrayColor(), fontSize: 10)
    // 微博正文
    lazy var contentLable = UILabel(color: UIColor.darkGrayColor(), fontSize: 15, mutiLines: true)

    // 配图
    let pictureLayout = UICollectionViewFlowLayout()
    lazy var pictureView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: self.pictureLayout)

    lazy var footerView:StatusFooterView = {

        let footerView = StatusFooterView()
        footerView.backgroundColor = UIColor.darkGrayColor()

        return footerView
    }()
}

// 配图cell
private class StatusPictureCell: UICollectionViewCell {

    ///  图像地址
    var imageURL: NSURL? {

        didSet{
            iconView.sd_setImageWithURL(imageURL)
            
            gifViewToIcon.hidden = !(imageURL?.absoluteString.pathExtension.lowercaseString == "gif")
        }
    }

    override init(frame: CGRect) {

        super.init(frame: frame)
        // 设置图片的填充模式 ，下面两句代码需要同时使用
        iconView.contentMode = UIViewContentMode.ScaleAspectFill
        iconView.clipsToBounds = true

        addSubview(iconView)
        addSubview(gifViewToIcon)

        iconView.ff_Fill(self)
        gifViewToIcon.ff_AlignInner(ff_AlignType.BottomRight, referView: self, size: nil)
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private lazy var iconView = UIImageView()
    private lazy var gifViewToIcon: UIImageView = {
        
        let v = UIImageView()
        v.image = UIImage(named: "timeline_image_gif")
        v.hidden = true
        
        return v
    }()
    
}


// 底部视图
class StatusFooterView: UIView {

    override init(frame: CGRect) {

        super.init(frame: frame)
        
        addSubview(lineView)
        lineView.addSubview(forwardButton)
        lineView.addSubview(commentButton)
        lineView.addSubview(likeButton)



        // 设置布局
        ff_HorizontalTile([lineView], insets: UIEdgeInsets(top: 1, left: 0, bottom: 0, right: 0))
        lineView.ff_HorizontalTile([forwardButton,commentButton,likeButton], insets: UIEdgeInsetsZero)



    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    lazy var forwardButton: UIButton = UIButton(title: "转发", imageName: "timeline_icon_retweet", fontSize: 12)
    lazy var commentButton: UIButton = UIButton(title: "评论", imageName: "timeline_icon_comment", fontSize: 12)
    lazy var likeButton: UIButton = UIButton(title: "赞", imageName: "timeline_icon_unlike", fontSize: 12)
    lazy var lineView: UIView = {

        let v = UIView()
        v.backgroundColor = UIColor.whiteColor()
        return v
    }()

}
